/*
 DATE：2016-10-12
 AUTH：Abel.lin
 settings 参数说明
 -----
 url -----------------------------数据请求地址
 data ----------------------------表格数据（json数组），url、data都有值时优先使用data的数据
 params --------------------------请求参数,json对象或k1=v1&k2=v2&k3=v3格式
 trId ----------------------------
 pageNO --------------------------当前页，默认1
 pageSize ------------------------分页大小，默认15
 success -------------------------表格渲染成功后回调方法
 checkEvent ----------------------选择框change事件
 selectedRows --------------------返回选中对应行数据
 ------------------------------ */
(function($){
	$.fn.abelGrid=function(opt){
		var $table = $(this);
		var $page = $table.next('.grid-page');
		if($page.length==0){
			$table.after('<div class="m-page grid-page"></div>');
			$page = $table.next('.grid-page');
		}
		// 默认值
		opt=$.extend({
			url:'',
			data:null,
			params:{},
			trId:'',
			pageNO:1,
			pageSize:15,
			pageCount:0,
			itemTotal:0,
			selectedRows:[],
			selectedAll:[],
			success:function(){},
			checkEvent:function(){}
		},opt || {});
		opt.params.pageNO = opt.pageNO;
		opt.params.pageSize = opt.pageSize;

		/**=======================page event begin===============================**/
		$page.on("click",'.pageprv',function(){
			if(opt.pageNO <= 1){
				return false;
			}
			opt.pageNO = opt.pageNO - 1;
			opt.reLoad();
		})
		$page.on("click",'.pagenxt',function(){
			if(opt.pageNO >= opt.pageCount){
				return false;
			}
			opt.pageNO = opt.pageNO + 1;
			opt.reLoad();
			//pageshow(opt.pageNO,opt.pageCount);
		})
		$page.on("click",'a.pgno',function(){
			opt.pageNO = Number($(this).text());
			opt.reLoad();
			//pageshow(opt.pageNO,opt.pageCount);
		})
		$page.on("click",'a.first,a.last',function(){
			if($(this).hasClass('z-dis')){
				return false;
			}
			if($(this).hasClass('first')){
				opt.pageNO = 1;
			}else{
				opt.pageNO = opt.pageCount;
			}
			opt.reLoad();
			//pageshow(opt.pageNO,opt.pageCount);
		})
		/**=======================page event end===============================**/

		var init=function(respData){
			$table.find('tbody').remove();

			var $tableTH = $table.find('thead th');

			var bodyTR = '<tbody>';

			var dataRows = respData;
			if(dataRows == undefined && (respData instanceof Array)){
				dataRows = respData;
			}

			if(dataRows.length > 0) {
				//渲染表格数据
				$.each(dataRows, function (i, row) {
					var trId = '';
					if(!isEmpty(opt.trId) && !isEmpty(row[opt.trId])){
						trId = 'g_id="'+row[opt.trId]+'"';
					}
					bodyTR += '<tr '+trId+'>';
					$tableTH.each(function (j) {
						var thName = $(this).attr('name');
						var className = $(this).attr('td-class');   //设置td的class
						var isTitle = $(this).attr('td-title');     //设置td的title展示原值
						var isTitleFmt = $(this).attr('td-titleFmt'); //设置td的title展示格式后的值
						var attr = $(this).attr('td-attr');
						var tdVal = row[thName];
						var title = '';

						if(className == undefined || className == null){
							className = '';
						}
						if(className.indexOf('td_nowrap') >= 0){
							title = tdVal;
						}
						if(isTitle=='true'){
							title = tdVal;
						}

						var serialNO = (parseInt(opt.pageNO)-1)*parseInt(opt.pageSize)+(i + 1);

						if ($(this).attr('columnType') == 'checkbox') {
							tdVal = '<input type="checkbox" name="' + thName + '" value="' + tdVal + '">';
						} else if ($(this).attr('columnType') == 'checkbox_serial') {
							tdVal = '<input type="checkbox" name="' + thName + '" value="' + tdVal + '" id="ckb_' + serialNO + '"><label for="ckb_' + serialNO + '" class="input-all">' + serialNO + '</label>';
						} else if ($(this).attr('columnType') == 'radio') {
							tdVal = '<input type="radio" name="' + thName + '" value="' + tdVal + '">';
						} else if ($(this).attr('columnType') == 'radio_serial') {
							tdVal = '<input type="radio" name="' + thName + '" value="' + tdVal + '" id="ckb_' + serialNO + '"><label for="ckb_' + serialNO + '" class="input-all">' + serialNO + '</label>';
						} else if ($(this).attr('columnType') == 'serial') {
							tdVal = serialNO;
						} else {
							var funName = $(this).attr('customFormat');
							try {
								if (funName) {
									var fun = eval(funName);
									tdVal = fun(row[thName], row, thName);
									if(isTitleFmt=='true'){
										title = tdVal;
									}
								}
							} catch (e) {

							}
							if (isEmpty(tdVal)) {
								tdVal = '--';
							}
						}

						if(!isEmpty(title)){
							title = 'title="'+title+'"';
						}
						if(isEmpty(attr)){
							attr = '';
						}else{
							try{
								var attrJson = eval( "(" + attr + ")" );
								attr = '';
								$.each(attrJson, function(k,v){
									attr += k + '="'+v+'"';
								})
							}catch (e){
								console.log(e.message);
							}
						}
						if(isEmpty(thName)){
							thName = '';
						}
						bodyTR += '<td name="' + thName + '" class="'+className+'" '+title+ attr + '>' + tdVal + '</td>';
					})
					bodyTR += '</tr>';
				})
			}else{
				bodyTR += '<tr><td colspan="'+$tableTH.length+'" style="text-align: center">暂无数据</td></tr>';
			}

			bodyTR += '</tbody>'
			$table.find('thead').after(bodyTR);

			if($tableTH.eq(0).attr('columnType') == 'checkbox' || $tableTH.eq(0).attr('columnType') == 'checkbox_serial'){
				$table.find('tr input[type=checkbox]').iCheck({
					checkboxClass: 'icheckbox_square-red',//iradio_square-red
					radioClass: 'icheckbox_square-red'
				});
			}else if($tableTH.eq(0).attr('columnType') == 'radio' || $tableTH.eq(0).attr('columnType') == 'radio_serial'){
				$table.find('tr input[type=radio]').iCheck({
					checkboxClass: 'iradio_square-red',
					radioClass: 'iradio_square-red'
				});
			}

			$table.off('change','th[columnType=checkbox] input[type=checkbox], th[columnType=checkbox_serial] input[type=checkbox]');
			$table.off('change','td[name='+$tableTH.eq(0).attr('name')+'] input');

			//全选
			$table.on('change','th[columnType=checkbox] input[type=checkbox], th[columnType=checkbox_serial] input[type=checkbox]',function(){
				$th = $(this).parents('th');
				if($(this).prop('checked')){
					$table.find('td[name='+$th.attr('name')+'] input[type=checkbox]').iCheck('check');
				}else{
					$table.find('td[name='+$th.attr('name')+'] input[type=checkbox]').iCheck('uncheck');
				}
				var checked = $(this).prop('checked');
				selected($tableTH, dataRows,checked,dataRows);
			})

			$table.on('change','td[name='+$tableTH.eq(0).attr('name')+'] input',function(){
				var uncheckedSize = $table.find('td[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').not("input:checked").length;
				if(uncheckedSize > 0){
					$table.find('th[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').iCheck('uncheck');
				}else{
					$table.find('th[name='+$tableTH.eq(0).attr('name')+'] input[type=checkbox]').iCheck('check');
				}

				var checked = $(this).prop('checked');
				var index = $(this).parents('tbody').children('tr').index($(this).parents('tr'));
				var curRow = dataRows[index];
				selected($tableTH, dataRows ,checked,curRow);
			})

			if($table.prev('.checked_cnt').length == 0){
				$table.before('<div class="checked_cnt" style="display: none"></div>')
			}
			//勾上存在的值
			$table.prev('.checked_cnt').find('.checked_item').each(function(){
				$table.find('td input[value='+$(this).attr('data-id')+']').iCheck('check');
			});
			//设置是否全选
			var uncheckedSize = $table.find('td input[type=checkbox]').not("input:checked").length;
			if (uncheckedSize > 0) {
				$table.find('th input[type=checkbox]').iCheck('uncheck');
			} else if($table.find('td input[type=checkbox]').length > 0){
				$table.find('th input[type=checkbox]').iCheck('check');
			}

			//opt.pageBar.call($table, respData);
			opt.success.call($table, respData);

		};

		//设置选择的数据
		var selected=function($tableTH, dataRows,checked,curRow){
			opt.selectedRows=[];
			opt.selectedAll=[];
			$table.find('td[name='+$tableTH.eq(0).attr('name')+'] input:checked').each(function(){
				var index = $(this).parents('tbody').children('tr').index($(this).parents('tr'));
				opt.selectedRows.push(dataRows[index]);
			})
			$table.prev('.checked_cnt').find('.checked_item').each(function(){
				opt.selectedAll.push($(this).attr('data-id'));
			})
			opt.checkEvent.call($table, opt.selectedRows, checked, curRow);
		};

		var pageshow = function(cp,tp){
			if(cp <= 0 || tp > opt.pageCount){
				return false;
			}
			var sp = cp - 2;//startpage
			var ep = cp + 2;//endpage
			var eoff = ep - tp;//tp:totalpage
			if(eoff>0){
				sp = sp - eoff;
			}
			if(sp<=0){
				ep = ep -sp + 1;
			}
			var str = '';
			if(cp != 1){
				str = str + '<a href="#" class="first"><span class="pagearr">&lt;&lt;</span></a>';
				str = str + '<a href="#" class="pageprv"><span class="pagearr">&lt;</span></a>';
			}else{
				str = str + '<a href="#" class="first z-dis"><span class="pagearr">&lt;&lt;</span></a>';
				str = str + '<a href="#" class="pageprv z-dis"><span class="pagearr">&lt;</span></a>';
			}

			for(var i= sp;i<=ep;i++){
				if(i>0&& i<=tp){
					if(i == cp)
						str = str + '<a href="#" class="pgno z-crt">'+i+'</a>';
					else
						str = str + '<a href="#" class="pgno">'+i+'</a>';
				}
			}

			if(cp != tp) {
				str = str + '<a href="#" class="pagenxt"><span class="pagearr">&gt;</span></a>';
				str = str + '<a href="#" class="last"><span class="pagearr">&gt;&gt;</span></a>';
			}else {
				str = str + '<a href="#" class="pagenxt z-dis"><span class="pagearr">&gt;</span></a>';
				str = str + '<a href="#" class="last z-dis"><span class="pagearr">&gt;&gt;</span></a>';
			}
			$page.html(str);
		}

		//加载数据
		opt.reLoad=function(params){
			if(opt.data != undefined && opt.data != null && opt.data.length > 0){
				init(opt.data);
			}else if(opt.url != undefined && opt.url != null && opt.url != ''){
				if(params) opt.params = params;

				if(typeof opt.params == 'string'){
					opt.params = 'pageNO='+opt.pageNO+'&pageSize='+opt.pageSize + '&'+ opt.params;
				}else if(typeof opt.params == 'object'){
					opt.params.pageNO = opt.pageNO;
					opt.params.pageSize = opt.pageSize;
				}

				$.ajax({
					type:'post',
					url:opt.url,
					data:opt.params,
					dataType:'json',
					success:function(resp){
						init(resp.data);
						opt.itemTotal = resp.total;
						if(opt.itemTotal>0){
							$page.html('');
							if(!opt.pageNO) opt.pageNO = 1;
							opt.pageCount = parseInt(opt.itemTotal/opt.pageSize)+(opt.itemTotal%opt.pageSize==0?0:1);
							if(opt.pageNO > opt.pageCount){
								opt.pageNO = opt.pageCount;
							}
							pageshow(opt.pageNO,opt.pageCount);
						}else{
							$page.remove();
						}

					}, error: function (request) {
						layer.alert('操作失败', {icon: 0});
					}
				})
			}
		}

		//判断字符串是否为空
		function isEmpty(s) {
			return ((s == undefined || s == null || s === '') ? true : false);
		}

		opt.reLoad();

		return opt;
	};
})(jQuery);